package com.ruoyi.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.ArticleInfo;
import com.ruoyi.system.dto.article.PageArticleDto;
import com.ruoyi.system.mapper.ArticleInfoMapper;
import com.ruoyi.system.service.IArticleInfoService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 文章管理 服务实现类
 * </p>
 *
 * @author yanfu
 * @since 2024-04-07
 */
@Service
public class ArticleInfoServiceImpl extends ServiceImpl<ArticleInfoMapper, ArticleInfo> implements IArticleInfoService {

    @Override
    public boolean save(ArticleInfo articleInfo) {
//        articleInfo.setId(IdUtil.getSnowflakeNextId());
        List<ArticleInfo> articleInfos = getBaseMapper().selectList(new LambdaQueryWrapper<ArticleInfo>()
                .eq(ArticleInfo::getTitle, articleInfo.getTitle()));
        if (!articleInfos.isEmpty()) {
            throw new ServiceException("已存在相同标题文章");
        }
        int insert = getBaseMapper().insert(articleInfo);
        return true;
    }

    @Override
    public int update(ArticleInfo articleInfo) {
        int i = getBaseMapper().updateById(articleInfo);
        return i;
    }

    @Override
    public void delete(List<Long> ids) {
        getBaseMapper().deleteBatchIds(ids);
//        delete(ids);
    }

    @Override
    public ArticleInfo selectById(Long id) {
        ArticleInfo articleInfo = getBaseMapper().selectById(id);
        return articleInfo;
    }


    @Override
    public Page<ArticleInfo> pageCulvert(PageArticleDto dto) {
        Page<ArticleInfo> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        page = baseMapper.selectPageArticle(page, dto);
        return page;
    }

    @Override
    public List<ArticleInfo> selectByList() {
        List<ArticleInfo> articleInfos = getBaseMapper().selectList(new LambdaQueryWrapper<ArticleInfo>()
                .eq(ArticleInfo::getStatus, "1")
                .orderByDesc(ArticleInfo::getCreateTime).last("limit 5")
        );
        return articleInfos;
    }
}
